package com.lcz.musicplay.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.widget.Toast;

import com.lcz.musicplay.config.Constants;
import com.lcz.musicplay.utils.MediaUtils;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by hp on 2016/8/22.
 */
public class MusicService extends Service implements MediaPlayer.OnErrorListener, MediaPlayer.OnPreparedListener,
        MediaPlayer.OnCompletionListener, AudioManager.OnAudioFocusChangeListener {
    private MediaPlayer player;//媒体控件
    private Timer timer;//时间控制器
    private Messenger messenger;//消息机制

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    /*------------生命周期-----------------*/

    @Override
    public void onCreate() {
        super.onCreate();
        player = new MediaPlayer();
        //设置监听器
        player.setOnErrorListener(this);//资源出错
        player.setOnPreparedListener(this);//初始化准备
        player.setOnCompletionListener(this);//准备完成
        //创建audioManger 音频焦点处理来电时停止播放
        AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        int result = audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (messenger == null) {
            messenger = (Messenger) intent.getExtras().get("messenger");
        }
        //播放模式
        String option = intent.getStringExtra("option");
        switch (option) {
            case "播放":
                String path = intent.getStringExtra("path");
                play(path);
                break;
            case "暂停":
                pause();
                break;
            case "继续":
                continuePlay();
                break;
            case "进度":
                int progress = intent.getIntExtra("progress", -1);
                seekPlay(progress);
                break;
            case "停止":
                stop();
                break;
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    /*------------生命周期-----------------*/
     /*------------音乐播放设置-----------------*/
    /*开始播放*/
    public void play(String path) {
        try {
            player.reset();//Idle
            player.setDataSource(path);//设置数据
            player.prepare();//开始准备
            player.start();//开始播放
            //设置播放状态标记
            MediaUtils.CURSTATE = Constants.STATE_PLAY;
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /*暂停播放*/
    public void pause() {
        if (player != null && player.isPlaying()) {
            player.pause();
            //设置播放状态标记
            MediaUtils.CURSTATE = Constants.STATE_PAUSE;
        }
    }

    /*继续播放*/
    public void continuePlay() {
        if (player != null && !player.isPlaying()) {
            player.start();
            //设置播放状态标记
            MediaUtils.CURSTATE = Constants.STATE_PLAY;
        }
    }

    /*进度播放*/
    public void seekPlay(int progress) {
        if (player != null && player.isPlaying()) {
            player.seekTo(progress);
            //设置播放状态标记
            MediaUtils.CURSTATE = Constants.STATE_PLAY;
        }
    }

    /*停止播放*/
    public void stop() {
        if (player != null) {
            player.stop();
            //设置播放状态标记
            MediaUtils.CURSTATE = Constants.STATE_STOP;
        }
    }

    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        Toast.makeText(getApplicationContext(), "资源有问题", Toast.LENGTH_SHORT).show();
        return true;
    }

    @Override
    public void onPrepared(MediaPlayer mp) {
        //当前进度条进度相关设置
        if (timer == null) {
            timer = new Timer();
        }
        timer.schedule(new TimerTask() {
            @Override
            public void run() {

                try {
                    //总时长
                    int duration = player.getDuration();
                    //当前播放位置
                    int currentPosition = player.getCurrentPosition();
                    Message msg = Message.obtain();
                    msg.arg1 = duration;
                    msg.arg2 = currentPosition;
                    msg.what = Constants.MSG_ONPREPARED;
                    messenger.send(msg);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        }, 0, 1000);

    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        try {
            //发送消息告诉activity歌曲播放完毕，进行播放模式判断
            Message msg = Message.obtain();
            msg.what = Constants.MSG_ONCOMPLETION;
            messenger.send(msg);
        } catch (RemoteException e) {
            e.printStackTrace();
        }

    }
     /*------------音乐播放设置-----------------*/

    /**
     * ---------------音频焦点处理相关的方法---------------
     **/
    @Override
    public void onAudioFocusChange(int focusChange) {
        switch (focusChange) {
            case AudioManager.AUDIOFOCUS_GAIN://你已经得到了音频焦点。 
                // resume playback
                player.start();
                player.setVolume(1.0f, 1.0f);
                break;
            case AudioManager.AUDIOFOCUS_LOSS://你已经失去了音频焦点很长时间了。你必须停止所有的音频播放
                // Lost focus for an unbounded amount of time: stop playback and release media player
                if (player.isPlaying())
                    player.stop();
                player.release();
                player = null;
                break;
            case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT://你暂时失去了音频焦点
                // Lost focus for a short time, but we have to stop
                // playback. We don't release the media player because playback
                // is likely to resume
                if (player.isPlaying())
                    player.pause();
                break;
            case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK://你暂时失去了音频焦点，但你可以小声地继续播放音频（低音量）而不是完全扼杀音频。
                // Lost focus for a short time, but it's ok to keep playing
                // at an attenuated level
                if (player.isPlaying())
                    player.setVolume(0.1f, 0.1f);
                break;
        }

    }

}
